package com.ddone.helper;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * @author ddone
 * @date 2024/3/30-18:30
 */
public class JwtHelper {
    private static final long tokenExpiration = 365L * 24 * 60 * 60 * 1000;
    private static final String tokenSignKey = "123456";

    public static String createToken(Long userId, String username){

        return Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static Long getUserId(String token){
        try {
            if (StringUtils.isEmpty(token)) return  null;
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims body = claimsJws.getBody();
            Integer userId = (Integer) body.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String username = "root";
        Long userId = 12345L;

        String token = JwtHelper.createToken(userId, username);

        Long parseUserId = JwtHelper.getUserId(token);
        String parseUserName = JwtHelper.getUsername(token);

        System.out.println("=======================");

    }

}
